package com.pengpeng.sheepfoldmall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pengpeng.common.constant.WareConstant;
import com.pengpeng.common.utils.R;
import com.pengpeng.sheepfoldmall.ware.dao.PurchaseDetailDao;
import com.pengpeng.sheepfoldmall.ware.entity.PurchaseDetailEntity;
import com.pengpeng.sheepfoldmall.ware.service.PurchaseDetailService;
import com.pengpeng.sheepfoldmall.ware.service.WareSkuService;
import com.pengpeng.sheepfoldmall.ware.vo.MergeVo;
import com.pengpeng.sheepfoldmall.ware.vo.PurchaseDoneVo;
import com.pengpeng.sheepfoldmall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pengpeng.common.utils.PageUtils;
import com.pengpeng.common.utils.Query;

import com.pengpeng.sheepfoldmall.ware.dao.PurchaseDao;
import com.pengpeng.sheepfoldmall.ware.entity.PurchaseEntity;
import com.pengpeng.sheepfoldmall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<PurchaseEntity> queryWrapper = new LambdaQueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and(wrapper -> {
                wrapper.eq(PurchaseEntity::getId, Integer.parseInt(key)).or().eq(PurchaseEntity::getWareId, Integer.parseInt(key)).or()
                        .like(PurchaseEntity::getPhone, key).eq(PurchaseEntity::getAssigneeName, key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            queryWrapper.eq(PurchaseEntity::getStatus, status);
        }
        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params),queryWrapper);

        return new PageUtils(page);
    }

    /**
     * 查询未被领取的采购单列表(查询新建和已分配的采购单)
     */
    @Override
    public PageUtils queryUnreceiveList(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params),
                new LambdaQueryWrapper<PurchaseEntity>().eq(PurchaseEntity::getStatus,"0").or().eq(PurchaseEntity::getStatus,"1"));

        return new PageUtils(page);
    }

    /**
     * 合并采购需求
     */
    @Transactional
    @Override
    public R mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();

        //若合并采购需求时没有选择对应采购单，则新建采购单并合并采购需求
        if (purchaseId == null){
            //新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            //默认状态为新建
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setCreateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        PurchaseEntity purchase = this.getById(purchaseId);
        if (purchase.getStatus() == WareConstant.PurchaseStatusEnum.RECEIVED.getCode() ||
        purchase.getStatus() == WareConstant.PurchaseStatusEnum.FINISHED.getCode() ||
        purchase.getStatus() == WareConstant.PurchaseStatusEnum.HAS_ERROR.getCode() ){
            return R.error("该采购单已不可合并整单，请确定采购单状态是否为[新建]或[已分配]");
        }
        //获取采购需求列表
        List<Long> purchaseItemIds = mergeVo.getItems();

        Collection<PurchaseDetailEntity> purchaseDetailEntityCollection = purchaseDetailService.listByIds(purchaseItemIds);
        for (PurchaseDetailEntity purchaseDetailEntity : purchaseDetailEntityCollection) {
            if (purchaseDetailEntity.getStatus() != WareConstant.PurchaseDetailStatusEnum.CREATED.getCode()){
                return R.error("该采购需求已不可合并整单，请确定采购需求状态是否为[新建]”");
            }
        }

        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntities = purchaseItemIds.stream().map(id -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(id);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        //执行采购需求的批量修改
        purchaseDetailService.updateBatchById(purchaseDetailEntities);

        //合并采购单后，更新采购单的更新时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
        return R.ok();
    }

    /**
     * 业务员领取采购单
     * @param ids
     */
    @Transactional
    @Override
    public void receivedPurchase(List<Long> ids) {
        // 1.先确定采购单的状态是不是新建或已分配，只有这两种状态才能够被业务员领取
        List<PurchaseEntity> purchaseEntityList = ids.stream().map(id -> {
            //先根据id获取采购单实体
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(purchase -> {
            //过滤出所有状态为新建或已分配的采购单
            if (purchase.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    purchase.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            } else {
                return false;
            }
        }).map(purchase -> {
            //将过滤出来的所有实体的状态转换为“已领取”
            purchase.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
            purchase.setUpdateTime(new Date());
            return purchase;
        }).collect(Collectors.toList());
        // 2.改变采购单的状态（已领取）
        this.updateBatchById(purchaseEntityList);

        // 3.改变采购需求的状态为（正在采购）
        purchaseEntityList.forEach(purchase -> {
            LambdaQueryWrapper<PurchaseDetailEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(PurchaseDetailEntity::getPurchaseId,purchase.getId());

            List<PurchaseDetailEntity> list = purchaseDetailService.list(queryWrapper);
            List<PurchaseDetailEntity> purchaseDetailEntityList = list.stream().map(purchaseDetail -> {
                purchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.PURCHASING.getCode());
                return purchaseDetail;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailEntityList);
        });
    }

    /**
     * 业务员完成采购单
     */
    @Transactional
    @Override
    public R finishPurchase(PurchaseDoneVo purchaseDoneVo) {

        // 1.改变采购项状态
        List<PurchaseDetailEntity> purchaseDetailEntityList = new ArrayList<>();  //创建要批量修改的list
        boolean flag = true;  //创建一个布尔值用于判断采购单的整体状态
        //循环遍历每一个采购需求
        for (PurchaseItemDoneVo item : purchaseDoneVo.getItems()) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            //如果采购需求的状态为‘采购失败’
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HAS_ERROR.getCode()){
                //设置采购需求的状态与失败原因
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HAS_ERROR.getCode());
                purchaseDetailEntity.setReason(item.getReason());
                flag = false;
            }else {
                //如果采购需求的状态为‘采购成功’，则设置状态为采购成功并入库
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISHED.getCode());

                //先获取到入库所需要的信息
                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());
                // 3.将采购成功采购项的进行入库
                wareSkuService.addStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());

            purchaseDetailEntityList.add(purchaseDetailEntity);
        }
        //批量修改
        purchaseDetailService.updateBatchById(purchaseDetailEntityList);

        // 2.改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVo.getId());
        //采购需求全部采购成功采购单才成功，否则采购单状态为‘有异常’
        if (flag == true){
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISHED.getCode());
        }else {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HAS_ERROR.getCode());
        }
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

        return R.ok();
    }
}